package com.caption.filter;

import cn.hutool.core.util.RandomUtil;
import com.caption.support.TxContextHolder;
import com.caption.util.SnowflakeIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 *网关权限验证
 */
@Component
@Slf4j
public class AuthenticateFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       // String requestUrl = exchange.getRequest().getPath().toString();
        //获取token
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("Authorization");
        log.info("gateway token:{}",token);
        String txnId = RandomUtil.randomString(8);
        //传递交易流水号
        request.mutate().header("txnId", txnId).build();
        log.info("gateway txnId:{}",txnId);
        TxContextHolder.getCurrentContext().add("userId","ssa");

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
